/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xjh.him.fragment.session;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.xjh.him.R;
import com.xjh.him.activity.chat.ChatActivity;
import com.xjh.him.adapter.SessionAdapter;
import com.xjh.him.adapter.entity.Chat;
import com.xjh.him.adapter.entity.ChatMessage;
import com.xjh.him.adapter.entity.Session;
import com.xjh.him.adapter.entity.SessionMember;
import com.xjh.him.core.BaseFragment;
import com.xjh.him.databinding.FragmentSessionBinding;
import com.xjh.him.dto.UpdateNewestMsgDTO;
import com.xjh.him.dto.friend.FriendDTO;
import com.xjh.him.dto.user.UserDTO;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.popupwindow.popup.XUISimplePopup;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.display.DensityUtils;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.OnItemLongClickListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Page
public class SessionFragment extends BaseFragment<FragmentSessionBinding> {
    public static final int PAGE_CODE = 15546;
    private SessionAdapter mAdapter;

    @NonNull
    @Override
    protected FragmentSessionBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentSessionBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected void initViews() {
        WidgetUtils.initRecyclerView(binding.sessionList);

        String listSessionUrl = Utils.getWebServerApiUrl(requireActivity(), getString(R.string.api_user_session_list));
        SimpleCallBack<List<Session>> listSessionCB = new SimpleCallBack<List<Session>>() {
            @Override
            public void onSuccess(List<Session> response) throws Throwable {
                mAdapter = new SessionAdapter(requireActivity(), response);
                binding.sessionList.setAdapter(mAdapter);
                mAdapter.setItemClickListener(mItemClickListener);
                mAdapter.setItemLongClickListener(mItemLongClickListener);
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.toast(e.getDisplayMessage());
            }
        };
        Utils.doGet(listSessionUrl, listSessionCB);
    }

    /**
     * 添加会话
     * @param session
     */
    public void addSessionItem(Session session) {
        List<Session> listData = mAdapter.getListData();
        int idx = listData.size();
        for (int i = 0; i < listData.size(); i++) {
            if (!listData.get(i).getIsTop()) {
                idx = i;
                break;
            }
        }
        listData.add(idx, session);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新最新消息
     * @param msgDTO
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void updateNewestMsg(UpdateNewestMsgDTO msgDTO) {
        List<Session> listData = mAdapter.getListData();
        int idx = -1;
        for (int i = 0; i < listData.size(); i++) {
            Session item = listData.get(i);
            if (item.getTargetId().equals(msgDTO.getGroupId()) &&
                    item.getGroupType().equals(msgDTO.getGroupType())) {
                idx = i;
                break;
            }
        }
        if (idx != -1) {
            Session session = listData.get(idx);
            if (ChatMessage.TYPE_IMAGE.equals(msgDTO.getMsgType())) {
                msgDTO.setMsgContent("[图片]");
            }
            if (Session.GROUP_TYPE_MULTIPLE.equals(msgDTO.getGroupType())) {
                msgDTO.setMsgContent(msgDTO.getSenderNickname() + "：" + msgDTO.getMsgContent());
            }
            session.setNewestMsg(msgDTO.getMsgContent());
            mAdapter.notifyItemChanged(idx);
        }else {
            XToastUtils.error("groupId: " + msgDTO.getGroupId() + " not found");
        }
    }

    /**
     * 消息item长按展示弹出框，置顶或删除
     */
    private OnItemLongClickListener mItemLongClickListener = (view, adapterPosition) -> {
        List<Session> items = mAdapter.getListData();
        Session session = items.get(adapterPosition);
        String[] popupItemList = getResources().getStringArray(
                session.getIsTop() ? R.array.msg_item_popup_list_cancel_top :
                        R.array.msg_item_popup_list_top
        );
        XUISimplePopup mListPopup;
        mListPopup = new XUISimplePopup(getContext(), popupItemList)
            .create(DensityUtils.dip2px(getContext(), 80), (adapter, item, popupItemPosition) -> {
                if (popupItemPosition == 0) {
                    if (!session.getIsTop()) {
                        // 置顶
                        session.setIsTop(true);
                        items.remove(adapterPosition);
                        items.add(0, session);
                        if (adapterPosition < 10) {
                            binding.sessionList.scrollToPosition(0);
                        }
                    }else {
                        // 取消置顶
                        session.setIsTop(false);
                        if (items.size() > 1) {
                            items.remove(adapterPosition);
                            for (int i = adapterPosition; i < items.size(); i++) {
                                if (!items.get(i).getIsTop()) {
                                    items.add(i, session);
                                    binding.sessionList.scrollToPosition(Math.max(i - 2, 0));
                                    break;
                                }
                            }
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }else if (popupItemPosition == 1) {
                    // 删除
                    items.remove(adapterPosition);
                    mAdapter.notifyDataSetChanged();
                }
            })
            .setHasDivider(true);
        mListPopup.showDown(view);
    };

    /**
     * 消息item点击跳转聊天页
     */
    @SuppressLint("StringFormatMatches")
    private OnItemClickListener mItemClickListener = (view, adapterPosition) -> {
        Session session = mAdapter.getItem(adapterPosition);
        Chat chat = new Chat();
        chat.setGroupId(session.getTargetId());
        chat.setGroupType(session.getGroupType());
        chat.setGroupName(session.getGroupName());
        chat.setGroupAvatar(session.getGroupAvatar());
        chat.setTop(session.getIsTop());

        Map<String, Object> map = new HashMap<>();
        if (session.getGroupType().equals(Session.GROUP_TYPE_SINGLE)) {
            String findUserUrl = Utils.getWebServerApiUrl(requireActivity(),
                    String.format(getString(R.string.api_user_find_user), session.getFriendId()));
            SimpleCallBack<UserDTO> findUserCB = new SimpleCallBack<UserDTO>() {
                @Override
                public void onSuccess(UserDTO userDTO) throws Throwable {
                    FriendDTO friendDTO = new FriendDTO();
                    friendDTO.setId(userDTO.getId());
                    friendDTO.setNickname(userDTO.getNickname());
                    friendDTO.setAvatarUrl(userDTO.getAvatarUrl());
                    map.put(ChatActivity.KEY_CHAT, chat);
                    map.put(ChatActivity.KEY_FRIEND_DTO, friendDTO);

                    ActivityUtils.startActivityForResultWithBundle(
                            requireActivity(),
                            ChatActivity.class,
                            PAGE_CODE,
                            map
                    );
                }

                @Override
                public void onError(ApiException e) {
                    XToastUtils.toast(e.getDisplayMessage());
                }
            };
            Utils.doGet(findUserUrl, findUserCB);
        }else {
            String listMemberUrl = Utils.getWebServerApiUrl(requireActivity(),
                    String.format(getString(R.string.api_user_group_member_list), session.getTargetId()));
            SimpleCallBack<List<SessionMember>> listMemberCB = new SimpleCallBack<List<SessionMember>>() {
                @Override
                public void onSuccess(List<SessionMember> list) throws Throwable {
                    map.put(ChatActivity.KEY_CHAT, chat);
                    map.put(ChatActivity.KEY_MEMBER_LIST, JSON.toJSONString(list));
                    ActivityUtils.startActivityForResultWithBundle(
                            requireActivity(),
                            ChatActivity.class,
                            PAGE_CODE,
                            map
                    );
                }

                @Override
                public void onError(ApiException e) {
                    XToastUtils.toast(e.getDisplayMessage());
                }
            };
            Utils.doGet(listMemberUrl, listMemberCB);
        }
    };

}
